// ****************Fifo.c********
//   Pointer implementation of the FIFO for the MC68HC12
// Jonathan W. Valvano 1/27/09

//  This example accompanies the books
//   "Embedded Microcomputer Systems: Real Time Interfacing",
//         Engineering, copyright (c) 2006,
//   "Introduction to Embedded Microcomputer Systems: 
//    Motorola 6811 and 6812 Simulation", Thomson, copyright (c) 2002

// Copyright 2009 by Jonathan W. Valvano, valvano@mail.utexas.edu 
//    You may use, edit, run or distribute this file 
//    as long as the above copyright notice remains 

#include "Fifo.h"
#include "Accel.h"

// Number of 16-bit values in the Fifo
//   the FIFO is full when it has FifoSize-1 entries 
Accel_TData static *PutPt;  // Pointer of where to put next 
Accel_TData static *GetPt;  // Pointer of where to get next 
                               // FIFO is empty if PutPt=GetPt 
                               // FIFO is full  if PutPt+1=GetPt 
Accel_TData static Fifo[FIFOSIZE];  // The statically allocated fifo data

/*-----------------------Fifo_Init----------------------------
  Initialize fifo to be empty
  Inputs: none
  Outputs: none */
void Fifo_Init(void){
  PutPt = GetPt = &Fifo[0];   // Empty when PutPt=GetPt 
}

/*-----------------------Fifo_Put----------------------------
  Enter one character into the fifo
  Inputs: 16-bit data
  Outputs: true if data is properly saved
  Since this is called by interrupt handlers no sei,cli*/
unsigned short Fifo_Put(Accel_TData data){
Accel_TData *tempPt;
  tempPt = PutPt;
  *tempPt = data;  // try to Put data into fifo 
  tempPt++;
  if(tempPt==&Fifo[FIFOSIZE]){// need to wrap?
    tempPt = &Fifo[0];
  }
  if(tempPt == GetPt ){
    return(1);      // Failed, fifo was full
  }                
  else{
    PutPt = tempPt; // Success, so update pointer 
    return(0);
  }
}
/*-----------------------Fifo_Get----------------------------
  Remove one character from the fifo
  Inputs: pointer to place to save 16-bit data
  Outputs: true if data is valid */
unsigned short Fifo_Get(Accel_TData *datapt){
  if(PutPt == GetPt ){
    return(1);     // Empty if PutPt=GetPt
  }
  else{
    *datapt = *GetPt;   // store data into fifo
    GetPt++;            // setup pointer for next time
    if(GetPt==&Fifo[FIFOSIZE]){
      GetPt = &Fifo[0];
    }
    return(0);
  }
}


